"""
应用程序入口点
"""
import sys
import os
import traceback
from PyQt5.QtWidgets import QApplication

from app.core.service_initializer import ServiceInitializer
from app.ui.main_window import MainWindow
from app.utils.logger import Logger
from app.services.service_locator import ServiceLocator
from app.services.service_registry import register_services


def setup_environment():
    """
    设置环境
    """
    # 获取日志记录器
    logger = Logger.get_logger("setup_environment")
    
    # 确保必要的目录存在
    os.makedirs("data", exist_ok=True)
    os.makedirs("logs", exist_ok=True)
    os.makedirs("cache", exist_ok=True)
    
    # 创建新的音频缓存目录（无需依赖app.config_path）
    os.makedirs("音频缓存", exist_ok=True)
    
    # 尝试从配置获取app.config_path
    try:
        # 尝试从配置文件直接读取
        config_file = "data/config.json"
        if os.path.exists(config_file):
            import json
            with open(config_file, 'r', encoding='utf-8') as f:
                config_data = json.load(f)
                if 'app' in config_data and 'config_path' in config_data['app']:
                    app_config_path = config_data['app']['config_path']
                    logger.info(f"从配置文件获取app.config_path: {app_config_path}")
                    
                    # 创建配置路径下的音频缓存目录
                    audio_cache_dir = os.path.join(app_config_path, "音频缓存")
                    os.makedirs(audio_cache_dir, exist_ok=True)
                    logger.info(f"创建配置路径下的音频缓存目录: {audio_cache_dir}")
    except Exception as e:
        logger.error(f"从配置文件获取app.config_path失败: {str(e)}")


def main():
    """
    应用程序主函数
    """
    # 设置环境
    setup_environment()
    
    # 初始化日志
    logger = Logger.get_logger("main")
    logger.info("应用程序启动")
    
    try:
        # 创建 QApplication 实例
        app = QApplication(sys.argv)
        app.setApplicationName("直播评论助手")
        app.setApplicationVersion("1.0.0")
        
        # 初始化服务
        service_initializer = ServiceInitializer()
        service_initializer.initialize_services()
        
        # 创建主窗口
        main_window = MainWindow(service_initializer)
        main_window.show()
        
        # 设置退出处理
        app.aboutToQuit.connect(lambda: cleanup(service_initializer))
        
        # 运行应用程序
        sys.exit(app.exec_())
    except Exception as e:
        logger.error(f"应用程序发生错误: {str(e)}")
        logger.error(traceback.format_exc())
        
        # 尝试清理资源
        try:
            cleanup(service_initializer)
        except:
            pass
        
        sys.exit(1)


def cleanup(service_initializer):
    """
    清理资源
    
    @param service_initializer: 服务初始化器
    """
    logger = Logger.get_logger("main")
    logger.info("正在清理资源...")
    
    try:
        # 关闭所有服务
        service_initializer.shutdown_services()
        
        logger.info("资源清理完成")
    except Exception as e:
        logger.error(f"资源清理失败: {str(e)}")
        logger.error(traceback.format_exc())


if __name__ == "__main__":
    main()